<template>
	<view class="device-panel">
		<view class="header">
			<text class="name">{{ device.name || device.port }}</text>
			<text class="type">{{ device.type }}</text>
			<text class="rssi" v-if="device.rssi !== undefined">
				信号: {{ device.rssi }} dBm
			</text>
		</view>

		<view class="value-box">
			<text class="value">{{ displayValue }}</text>
			<button size="mini" @click="toggleUnit">
				切换单位 ({{ unit }})
			</button>
		</view>

		<view class="footer">
			<text class="status" :class="{ connected: device.connected }">
				{{ device.connected ? '已连接' : '未连接' }}
			</text>
			<button v-if="device.connected" size="mini" type="warn" @click="$emit('disconnect', device)">断开</button>
		</view>
	</view>
</template>

<script>

	export default {
		props: {
			device: Object
		},
		data() {
			return {
				value: '--',
				unit: 'mm'
			}
		},
		computed: {
			displayValue() {
				if (this.value === '--') return '--'
				return `${this.value} ${this.unit}`
			}
		},
		methods: {
			mmToInch(mm) {
				return (mm / 25.4).toFixed(3)
			},
			inchToMm(inch) {
				return (inch * 25.4).toFixed(3)
			},
			updateValue(data) {
				if (!data) return
				if (typeof data === 'object') {
					this.value = data.value
					this.unit = data.unit || 'mm'
				} else {
					this.value = data
				}
			},
			toggleUnit() {
				if (this.unit === 'mm') {
					this.value = this.mmToInch(this.value)
					this.unit = 'inch'
				} else {
					this.value = this.inchToMm(this.value)
					this.unit = 'mm'
				}
			}
		}
	}
</script>

<style>
	.device-panel {
		background: #f6f8fa;
		padding: 20rpx;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
	}

	.header {
		display: flex;
		justify-content: space-between;
	}

	.value-box {
		margin: 20rpx 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.value {
		font-size: 40rpx;
		font-weight: bold;
		color: #007aff;
	}

	.footer {
		display: flex;
		justify-content: space-between;
	}

	.status.connected {
		color: #4cd964;
	}
</style>